package crud

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

var jsTmpl = `
layui.use(["laytp"], function () {
    const funController = {};
	const html_prefix = "{{.__HTML_PREFIX__}}";
	const api_prefix = "{{.__API_PREFIX__}}";

    //静态页面地址前缀
    window.htmlPrefix = facade.compatibleHtmlPath(html_prefix);
    //后端接口地址前缀
    window.apiPrefix  = facade.compatibleApiRoute(api_prefix);

    //表格渲染
    funController.tableRender = function (where, page) {
        layui.table.render({
            elem: "#laytp-table"
            , limit: facade.getLimit(html_prefix)
            , id: "laytp-table"
            , url: facade.url(api_prefix + "index",{paging:1})
            , toolbar: "#default-toolbar"
            , defaultToolbar: [{
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
            }, 'filter', 'print', 'exports']
            , where: where
            , autoSort: false
            , method: "GET"
            , cellMinWidth: 80
            , skin: 'line'
            , loading: false
            , page: {
                curr: page
            }
            , parseData: function (res) { //res 即为原始返回的数据
                layui.laytpTable.setLimit(html_prefix, res.data.per_page);
                return facade.parseTableData(res, true);
            }
            , done: function(){
                layui.laytpTable.done();
            }
            , cols: [[
                {type: "checkbox"}
                , {field: "id", title: "ID", align: "center", width: 80}
                {{.__FIELD__}}
				
                , {field: "create_time", title: "创建时间", align: "center", width: 160}
                , {field: "operation", title: "操作", align: "center", fixed: 'right', toolbar: "#default-bar", width: 180}
            ]]
        });

        //监听数据表格顶部左侧按钮点击事件
        layui.table.on("toolbar(laytp-table)", function (obj) {
            //默认按钮点击事件，包括添加按钮和回收站按钮
            var defaultTableToolbar = layui.context.get("defaultTableToolbar");
            if (defaultTableToolbar.indexOf(obj.event) !== -1) {
                laytp.tableToolbar(obj);
            } else {
				let indexes = [];
                if (obj.event === "import") {
		            let options = {};
		            options.title = "导 入";
		            options.path = facade.compatibleHtmlPath(html_prefix) + "import.html";
		            indexes.push(facade.popupDiv(options));
		        }
				if (indexes.length === 1) return indexes.pop();
                else return [...indexes];
            }
        });

        //监听数据表格[操作列]按钮点击事件
        layui.table.on("tool(laytp-table)", function (obj) {
            var defaultTableTool = layui.context.get("defaultTableTool");
            if (defaultTableTool.indexOf(obj.event) !== -1) {
                laytp.tableTool(obj);
            } else {
				let indexes = [];
		        if (obj.event === "info") {
		            let options = {};
		            options.title = "详 情";
		            options.path = facade.compatibleHtmlPath(html_prefix) + "info.html";
		            indexes.push(facade.popupDiv(options));
		        } else if (obj.event === "list") {
		            let options = {};
		            options.title = "列 表";
		            options.path = facade.compatibleHtmlPath(html_prefix) + "list.html";
		            indexes.push(facade.popupDiv(options));
		        }

				if (indexes.length === 1) return indexes.pop();
                else return [...indexes];
			}
        });

        //监听表头排序事件
        layui.table.on('sort(laytp-table)', function(obj){
            layui.table.reloadData('laytp-table', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                , where: {
                    "order_param" : {
                        "field" : obj.field,
                        "type" : obj.type
                    }
                }
            });
        });
    };

    funController.tableRender();

    window.funController = funController;
});
`

func (g *cGlobal) MakeJs() error {
	err := os.MkdirAll(g.AppPath.JsPath, os.ModePerm)
	if err != nil {
		return err
	}

	tbInfo := g.TableSchema
	fields := make([]string, 0)

	if g.Field != nil {
		for key, val := range g.Field {
			if key == "id" || key == "create_time" || key == "update_time" || key == "delete_time" {
				continue
			}
			sVal := ""
			if key == "status" {
				sVal = `,{field:'status',title:'状态',align:'center',templet:function(d){
                    return laytpForm.tableForm.switch("status", d, {
                        "open": {"value": 1, "text": "正常"},
                        "close": {"value": 2, "text": "隐藏"}
                    });
                }}`
			} else if key == "user_id" {
				sVal = `,{field:'status',title:'用户',align:'center',templet:function(d){
                    return d.members ? d.members.nickname : ""
                }}`
			} else if key == "level_id" {
				sVal = `,{field:'status',title:'级别',align:'center',templet:function(d){
                    return d.levels ? d.levels.name : ""
                }}`
			} else if key == "shop_id" {
				sVal = `,{field:'status',title:'商品',align:'center',templet:function(d){
                    return d.shops ? d.shops.title : ""
                }}`
			} else if key == "owner_id" {
				sVal = `,{field:'status',title:'邀请人',align:'center',templet:function(d){
                    return d.owners ? d.owners.nickname : ""
                }}`
			} else if key == "article_id" {
				sVal = `,{field:'status',title:'邀请人',align:'center',templet:function(d){
                    return d.articles ? d.articles.en_title : ""
                }}`
			} else if key == "order_id" {
				sVal = `,{field:'status',title:'订单',align:'center',templet:function(d){
                    return d.orders ? d.orders.order_no : ""
                }}`
			} else {
				sVal = fmt.Sprintf(", {field: \"%v\", title: \"%v\", align: \"center\"}", key, val["name"])
			}

			fields = append(fields, sVal)
		}
	} else {
		for _, column := range tbInfo {
			if column["column"] == "id" || column["ctype"] == "datetime" || column["column"] == "create_time" || column["column"] == "update_time" || column["column"] == "delete_time" {
				continue
			}

			comment := column["comment"]
			label := comment
			sVal := ""
			if comment != "" {
				if idx := strings.Index(comment, "("); idx > 0 {
					label = comment[:idx]
					rules := comment[idx+1:]
					rules = strings.ReplaceAll(rules, "(", "")
					rules = strings.ReplaceAll(rules, ")", "")

					if strings.Index(comment, "radio") > 0 {
						rules = strings.ReplaceAll(rules, "radio:", "")
						var tmp []map[string]string
						err = json.Unmarshal([]byte(rules), &tmp)
						if err != nil {
							continue
						}

						switchVal := ""

						for _, sv := range tmp {
							if sv["id"] == "1" {
								switchVal += fmt.Sprintf(`"open": {"value": %v, "text": "%v"},`, sv["id"], sv["name"])
							} else {
								switchVal += fmt.Sprintf(`                                "close": {"value": %v, "text": "%v"},`, sv["id"], sv["name"])
							}
							switchVal += "\n"
						}

						sVal = fmt.Sprintf(`, {
                    field: "%v", title: "%v", align: "center", templet: function (d) {
                        return laytpForm.tableForm.switch("%v", d, {
                                %v
                            });
                    }
                }`, column["column"], label, column["column"], switchVal)
					} else {
						sVal = fmt.Sprintf(", {field: \"%v\", title: \"%v\", align: \"center\"}", column["column"], label)
					}
				}
			} else {
				label = column["column"]
				sVal = fmt.Sprintf(", {field: \"%v\", title: \"%v\", align: \"center\"}", column["column"], label)
			}

			fields = append(fields, sVal)
		}
	}

	m := map[string]string{
		"__HTML_PREFIX__": g.HtmlURI,
		"__API_PREFIX__":  g.JsURI,
		"__FIELD__":       strings.Join(fields, "\n"),
	}

	fileName := g.AppFiles.Js
	err = TemplateExec(fileName, jsTmpl, m)
	if err != nil {
		return err
	}

	return nil
}
